/// <reference path="../Declarations/forguncy.d.ts" />
/// <reference path="../Declarations/forguncy.Plugin.d.ts" />

class MermaidRendererCellType extends Forguncy.Plugin.CellTypeBase {
    createContent() {
        const uniqueId = `mermaid-rendering-area-${Date.now()}-${Math.floor(Math.random() * 10000)}`;
        this.mermaidContainerId = uniqueId;

        this.content = $(`
            <div class='mermaid-area' id='${uniqueId}' style='width:100%;height:100%;overflow:auto;'>
            </div>
        `);
        
        return this.content;
    }

    async onPageLoaded() {
        this.onFormulaResultChanged(this.CellElement.CellType.MermaidDefinition, result => {
            const diagramDefinition = this.evaluateFormula(result);
            this.initMermaid(diagramDefinition);
        });
    }

    async setValueToElement(_, value) {
        value = value?.toString() ?? "";
        this.initMermaid(value)
    }

    set_MermaidDefinition(value) {
        this.initMermaid(value)
    }

    async initMermaid(diagramDefinition) {
        if (diagramDefinition == null) {
            return;
        }

        const diagramArea = document.getElementById(this.mermaidContainerId);

        if (!diagramArea) {
            console.warn(`[MermaidRenderer]未找到对应 mermaid 容器: ${this.mermaidContainerId}`);
            return;
        }
        
        mermaid.initialize({
            startOnLoad: false, // 避免自动渲染
            suppressErrorRendering: true, // 抑制默认错误提示
        });

        try {
            // 清理输入（换行 + HTML 标签）
            const cleanDefinition = diagramDefinition
                .replace(/\\n/g, '\n')
                .replace(/<br\s*\/?>/gi, '\n')
                .trim();

            // 清空旧内容
            diagramArea.innerHTML = '';

            // 生成新的唯一渲染 ID（避免缓存）
            const renderId = `mermaid-${Date.now()}-${Math.floor(Math.random() * 1000)}`;

            // 渲染
            const {svg} = await mermaid.render(renderId, cleanDefinition);
            diagramArea.innerHTML = svg;
        } catch (parseError) {
            console.error('[MermaidRenderer]图表定义解析失败:', parseError);
            diagramArea.innerHTML = `
                <div style="margin: 0;display: grid;place-items: center;align-items: center;height: 100%;background-color: #ffffff;color: #111827;">
                    <div style="text-align: center;padding: 4rem 1rem;">
                        <p style="font-size: 1.125rem;font-weight: 600;color: #448EF7;margin: 0;">
                            Oops! 🤔
                        </p>
                        <h1 style="margin-top: 1rem;font-size: 3rem;font-weight: 600;letter-spacing: -0.02em;color: #111827;margin-bottom: 0;">
                            一点小意外
                        </h1>
                        <p style="margin-top: 1.5rem;font-size: 1.125rem;font-weight: 500;color: #6b7280;margin-bottom: 0;">
                            请检查一下图表定义文本是否合规 🛠️
                        </p>
                    </div>
                </div>
            `;
        }
    }
}
Forguncy.Plugin.CellTypeHelper.registerCellType("MermaidRenderer.MermaidRendererCellType, MermaidRenderer", MermaidRendererCellType);